/**
 * 校园地图初始化脚本（高德 2.0）
 * 说明：无需修改此文件中的 Key、坐标。请在 config.properties 中配置：
 *   amap.key, school.name, school.address, school.lng, school.lat
 */
(function(){
  // 安全兜底：无 Key 时给出提示，但仍渲染基础页面结构
  if (!AMAP_KEY) {
    console.warn("未配置高德 Key：请在 src/main/resources/config.properties 中添加 amap.key=你的Key");
  }
  // 通过 AMapLoader 按需加载
  AMapLoader.load({
    key: AMAP_KEY || 'INVALID_KEY',
    version: '2.0',
    plugins: ['AMap.ToolBar','AMap.Scale','AMap.HawkEye','AMap.ControlBar','AMap.MouseTool']
  }).then((AMap) => {
    const map = new AMap.Map('mapContainer', {
      zoom: 17,
      center: [LNG, LAT],
      viewMode: '3D',
      animateEnable: true,
      jogEnable: true,
    });

    // 常用控件
    map.addControl(new AMap.ToolBar());
    map.addControl(new AMap.Scale());
    map.addControl(new AMap.ControlBar());
    map.addControl(new AMap.HawkEye({isOpen:false}));

    // 园区主标记
    const marker = new AMap.Marker({
      position: [LNG, LAT],
      title: SCHOOL_NAME,
      offset: new AMap.Pixel(0, -12)
    });
    map.add(marker);

    // 文本标注（显眼显示园名）
    const text = new AMap.Text({
      text: SCHOOL_NAME,
      anchor:'bottom-center',
      draggable:false,
      cursor:'default',
      style:{
        'background-color':'#fff',
        'border':'1px solid #e8e8e8',
        'padding':'6px 10px',
        'border-radius':'8px',
        'box-shadow':'0 2px 10px rgba(0,0,0,.08)'
      },
      position: [LNG, LAT]
    });
    map.add(text);

    // 信息窗体
    const info = new AMap.InfoWindow({
      content: `<div style="min-width:220px;">
        <div style="font-weight:600;margin-bottom:6px;">${SCHOOL_NAME}</div>
        <div style="color:#666;margin-bottom:8px;">地址：${SCHOOL_ADDRESS}</div>
        <div style="display:flex;gap:6px;flex-wrap:wrap;">
          <a target="_blank" href="https://uri.amap.com/navigation?to=${LNG},${LAT},${encodeURIComponent(SCHOOL_NAME)}&mode=car&src=kindergarten">驾车</a>
          <a target="_blank" href="https://uri.amap.com/navigation?to=${LNG},${LAT},${encodeURIComponent(SCHOOL_NAME)}&mode=bus&src=kindergarten">公交</a>
          <a target="_blank" href="https://uri.amap.com/navigation?to=${LNG},${LAT},${encodeURIComponent(SCHOOL_NAME)}&mode=walk&src=kindergarten">步行</a>
        </div>
      </div>`,
      offset: new AMap.Pixel(0, -30)
    });
    info.open(map, [LNG, LAT]);

    // 点击标记切换信息窗
    marker.on('click', () => {
      info.open(map, [LNG, LAT]);
    });

    // 鼠标工具：支持框选、测距等（便于教职工导览）
    const mouseTool = new AMap.MouseTool(map);
    // 示例：双击地图退出编辑工具
    map.on('dblclick', function(){
      mouseTool.close(true);
    });

  }).catch((e) => {
    console.error("AMap 初始化失败：", e);
    const el = document.getElementById('mapContainer');
    if (el) el.innerHTML = '<div style="padding:20px;color:#f40;">地图加载失败：请检查网络或 Key 配置。</div>';
  });
})();
